package com.qianfeng.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBUtils {
	private static SqlSessionFactory factory;
	private static ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();
	static {
		InputStream is;
		try {
			is = Resources.getResourceAsStream("mybatis-config.xml");
			factory = new SqlSessionFactoryBuilder().build(is);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static <E> E getMapper(Class<E> clazz) {
		if (local.get() == null) {
			SqlSession session = factory.openSession(true);
			local.set(session);
		}
		E e = local.get().getMapper(clazz);
		return e;
	}

	public static void release() {
		SqlSession sqlSession = local.get();
		if (sqlSession != null) {
//			sqlSession.commit();

			sqlSession.close();
			local.remove();
		}
	}
}
